import React, { Component } from 'react';
import $ from 'jquery';
import {
  Modal,
  Button,
  Form,
  Col,
  InputGroup,
  FormControl
} from 'react-bootstrap';

import "./less/add.css";

import { function_add_project } from '../../actions/project';

class AddProject extends Component {

  state = {
    chatType: 1,
    nameError: false,
    urlError: false
  }

  handleSubmit () {
    let name = $(this.refs.name).val();
    if (name === "" || name.length > 10) {
      return this.setState({
        nameError: true,
        urlError: false
      });
    }
    let chatType = this.state.chatType;
    let notifyUrl = $(this.refs.notifyUrl).val();
    let notifySecret = $(this.refs.notifySecret).val();
    if(typeof notifySecret === "undefined") notifySecret = "";
    let reg = /(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-,@?^=%&:/~#]*[\w\-?^=%&/~#])?/;
    if (notifyUrl !== "" && !reg.test(notifyUrl)) {
      return this.setState({
        nameError: false,
        urlError: true
      });
    }
    this.setState({
      nameError: false
    });
    function_add_project(name, chatType, notifyUrl, notifySecret, this.props.dispatch);
    this.props.handleClose();
  }

  render () {
    return (
      <Modal className="addProjectBox" show={this.props.show} onHide={this.props.handleClose.bind(this)} animation={true}>
        <Modal.Header closeButton>
          <Modal.Title>创建项目</Modal.Title>
        </Modal.Header>
        <Modal.Body>
          <Form>
            <Form.Group>
              <Form.Label>项目名称</Form.Label>
              <Form.Control type="text" ref="name" className={this.state.nameError ? "error" : ""} placeholder="项目名称" />
            </Form.Group>

            <Form.Group>
              <Form.Label>消息通知（上线相关消息将通过这个钉钉/企业微信的webhook进行通知）</Form.Label>
              <Form.Row>
                <Col xs lg="2">
                  <Form.Control as="select" onChange={(event) => this.setState({chatType: parseInt(event.target.value)})}>
                    <option value="1">钉钉</option>
                    <option value="2">企业微信</option>
                  </Form.Control>
                </Col>
                <Col>
                    <InputGroup>
                      <FormControl type="url" ref="notifyUrl" className={this.state.urlError ? "error" : ""} placeholder="WebHook链接地址" />
                      {this.state.chatType === 1 ?
                      <FormControl ref="notifySecret" placeholder="WebHook密钥" />
                      : null}
                    </InputGroup>
                </Col>
              </Form.Row>
            </Form.Group>
          </Form>
        </Modal.Body>
        <Modal.Footer>
          <Button variant="secondary" onClick={this.props.handleClose.bind(this)}>
            取消
        </Button>
          <Button variant="primary" onClick={this.handleSubmit.bind(this)}>
            增加
        </Button>
        </Modal.Footer>
      </Modal>
    )
  }
}

export default AddProject;